package com.citycloud.ccuap.tc.sync.aspect;

import com.citycloud.ccuap.commons.db.SqlRestrictions;
import com.citycloud.ccuap.commons.json.JSONData;
import com.citycloud.ccuap.commons.sys.entity.SysProject;
import com.citycloud.ccuap.commons.sys.entity.SysUser;
import com.citycloud.ccuap.commons.sys.project.IProjectService;
import com.citycloud.ccuap.commons.sys.user.UserService;
import com.citycloud.ccuap.tc.sync.dto.UserDeptProjectRelDTO;
import com.citycloud.ccuap.tc.sync.dto.UserMessageDTO;
import com.citycloud.ccuap.tc.sync.constant.GlobalSyncOperation;
import com.citycloud.ccuap.tc.sync.constant.GlobalSyncType;
import com.citycloud.ccuap.tc.sync.dto.SyncDataDto;
import com.citycloud.ccuap.tc.sync.service.IMessageService;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;

/**
 * @author zjl
 * @date 2020/04/30 9:58
 */
@Aspect
@Component
public class UserUpdateAspect {
    @Autowired
    private UserService userService;
    @Autowired
    private IMessageService messageService;
    @Autowired
    private IProjectService projectService;

    @Pointcut("execution(* com.citycloud.ccuap.commons.sys.user.UserController.update())")
    public void update() {
    }

    @SuppressWarnings({"rawtypes", "unchecked"})
    @AfterReturning(value = "update()", returning = "key")
    public void update(JoinPoint joinPoint, Object key) throws Throwable {
        if (key instanceof JSONData) {
            JSONData jsonData = (JSONData) key;
            if (jsonData.getData() instanceof SysUser) {
                SysUser user = (SysUser) jsonData.getData();
                // 移除敏感信息
                user.setPassword(null);
                user.setDesPassword(null);
                sendMessage(user);
            }
        }

    }

    /**
     * 用户修改发送MQ对象消息
     *
     * @param user 用户对象
     */
    public void sendMessage(SysUser user) {
        if (user.getProjectId() == null) {
            // 查询用户关联站点记录
            List<UserDeptProjectRelDTO> relDTOList = getProjectUsers(Arrays.asList(user.getUserId()));
            for (UserDeptProjectRelDTO dto : relDTOList) {
                if (dto.getMqOff()) {
                    UserMessageDTO userMessage = new UserMessageDTO();
                    userMessage.build(user);
                    userMessage.setProjectId(dto.getProjectId());
                    userMessage.setDeptId(dto.getDeptId());

                    send(dto.getProjectId(), userMessage);
                }
            }
        } else {
            SysProject project = projectService.findById(user.getProjectId());
            if (project != null && project.getMqOff()) {
                UserMessageDTO userMessageDTO = new UserMessageDTO();
                userMessageDTO.build(user);

                send(user.getProjectId(), userMessageDTO);
            }
        }
    }


    private List<UserDeptProjectRelDTO> getProjectUsers(List<Long> userIds) {
        String userIdStr = StringUtils.join(userIds, ",");
        String sql = "select rel.rel_id as relId,rel.user_id as userId,rel.dept_id as deptId,rel.project_id as projectId,p.mq_off as mqOff from sys_user_dept_rel rel inner join sys_project p on rel.project_id = p.project_id ";
        sql += SqlRestrictions.in("rel.user_id", userIdStr);
        List<UserDeptProjectRelDTO> list = (List<UserDeptProjectRelDTO>) userService.selectList(UserDeptProjectRelDTO.class, sql);
        return list;
    }

    private void send(Long projectId, UserMessageDTO dto) {
        SyncDataDto<UserMessageDTO> result = SyncDataDto.of(GlobalSyncType.OBJECT_TYPE_USER,
                GlobalSyncOperation.UPDATED, projectId, dto);
        messageService.sendMessageByTopic(result,GlobalSyncType.TOPIC_USER_DEPT);
    }

}
